<template>
  <div class="mobile-frame">
    <van-nav-bar>
      <template #title>
        <van-search label="质检 " left-icon="" v-model="qrcode_str" placeholder="扫描条码" @search="onSearch" />
      </template>
      <template #right> </template>
    </van-nav-bar>
    <div style="padding-top: 10px; height: calc(100% - 42px - 54px); overflow: auto">
      <van-cell-group inset>
        <van-field label="业务类型" v-model="qrdoc.type" />
        <van-field label="单号" v-model="qrdoc.billcode" />
        <van-field label="条码" v-model="qrdoc.qrcode" />
        <van-field label="物料编码" v-model="qrdoc.materialcode" />
        <van-field label="物料名称" v-model="qrdoc.materialname" />
        <van-field label="待检数量" v-model="qrdoc.qty" />
        <van-field label="合格数量">
          <template #input>
            <van-stepper :min="0" :max="qrdoc.qty" v-model="qrdoc.qualified" @change="q_input" />
          </template>
        </van-field>
        <van-field label="不合格数">
          <template #input>
            <van-stepper :min="0" :max="qrdoc.qty" v-model="qrdoc.unqualified" @change="uq_input" />
          </template>
        </van-field>
      </van-cell-group>
    </div>
    <van-button type="primary" :disabled="qrdoc.unqualified === 0 && qrdoc.qualified === 0" block @click="submit">提交</van-button>
  </div>
</template>
<script lang="ts" setup>
import { useDbStore } from '@/stores/modules/database'
import { ref } from 'vue'
import { showDialog } from 'vant'
import { fill_ref_info, get_code_prefix, sum } from '@/utils/common'
import { e_code_prefix, e_material_storage_status, e_qc_status, e_stock_order_type } from '@/types/enum'
import { arrive_bill_define, qrcode_define } from '@/meta'
import type { bd_material } from '@/types/basedata'
import type { arrive_bill } from '@/types/billdata'

interface t_qrdoc {
  type: string
  qrcode: string
  billcode: string
  materialcode: string
  materialname: string
  qty: number
  qualified: number
  unqualified: number
  finished: number
}
const db = useDbStore()

const currentArrive = ref<arrive_bill>()
const qrcode_str = ref<string>()
const qrdoc = ref<t_qrdoc>({
  type: '',
  qrcode: '',
  billcode: '',
  materialcode: '',
  materialname: '',
  finished: 0,
  qty: 0,
  qualified: 0,
  unqualified: 0
})
const clearQrDoc = () => {
  qrdoc.value = {
    type: '',
    qrcode: '',
    billcode: '',
    finished: 0,
    materialcode: '',
    materialname: '',
    qty: 0,
    qualified: 0,
    unqualified: 0
  }
}
const onSearch = () => {
  const type = get_code_prefix(qrcode_str.value!)
  qrdoc.value.type = type
  qrdoc.value.qrcode = qrcode_str.value!
  const content = trimPrefix(qrcode_str.value!)
  qrcode_str.value = ''
  switch (e_code_prefix[type as keyof typeof e_code_prefix]) {
    case e_code_prefix.采购入库:
    case e_code_prefix.委外入库:
    case e_code_prefix.调拨入库:
    case e_code_prefix.退货入库:
      searchInBill(content)
      break
    case e_code_prefix.物码:
      searchInQr(content)
      break
  }
}
const trimPrefix = (str: string) => {
  const indexOf = str.indexOf('#')
  return str.substring(indexOf + 1, str.length)
}

const searchInBill = (key: string) => {
  const doc = db.arrive.find((r) => r.billcode === key && (r.status === e_qc_status.报检 || r.status === e_qc_status.部分完检))
  if (!doc) {
    showDialog({ title: '错误', message: '找不到单据' })
    return
  }
  currentArrive.value = doc

  fill_ref_info([doc], arrive_bill_define).then(() => {
    qrdoc.value.billcode = doc.billcode
    qrdoc.value.materialcode = (doc.material as bd_material).code
    qrdoc.value.materialname = (doc.material as bd_material).name
    qrdoc.value.qty = doc.arrive_qty - doc.qualified - doc.unqualified
    qrdoc.value.qualified = qrdoc.value.qty
    qrdoc.value.unqualified = 0
    qrdoc.value.finished = doc.qualified - doc.unqualified
  })
}
const searchInQr = (key: string) => {
  const doc = db.qrcode.find((r) => r.qrcode === key)
  if (!doc) {
    showDialog({ title: '错误', message: '找不到条码' })
    return
  }
  currentArrive.value = db.arrive.find((r) => r.billcode === doc.arrive_bill)
  fill_ref_info([doc], qrcode_define).then(() => {
    qrdoc.value.billcode = doc.arrive_bill
    qrdoc.value.materialcode = (doc.material as bd_material).code
    qrdoc.value.materialname = (doc.material as bd_material).name
    qrdoc.value.qty = doc.qty
    qrdoc.value.qualified = doc.status === e_material_storage_status.报检 ? doc.qty : 0
    qrdoc.value.unqualified = 0
    qrdoc.value.finished = doc.status === e_material_storage_status.报检 ? doc.qty : 0
  })
}
const q_input = () => {
  qrdoc.value.unqualified = qrdoc.value.qty - qrdoc.value.qualified
}
const uq_input = () => {
  qrdoc.value.qualified = qrdoc.value.qty - qrdoc.value.unqualified
}
const submit = () => {
  if (e_code_prefix[qrdoc.value.type as keyof typeof e_code_prefix] === e_code_prefix.物码) {
    submit_by_ml()
  } else {
    if (currentArrive.value?.code_after_qc) {
      submit_by_arrive_without_code()
    } else {
      submit_by_arrive()
    }
  }
  if (currentArrive!.value!.qualified + currentArrive!.value!.unqualified === currentArrive!.value!.arrive_qty) {
    currentArrive!.value!.status = e_qc_status.检验完成
  } else if (currentArrive!.value!.qualified > 0) {
    currentArrive!.value!.status = e_qc_status.部分完检
  }
  db.saveArriveCode()
}
const submit_by_arrive = () => {
  if (!currentArrive.value?.code_after_qc && qrdoc.value!.unqualified > 0) {
    showDialog({ title: '错误', message: '需要扫物码录入不合格数量' })
    return
  }
  const qrcodes = db.qrcode.filter(
    (r) => r.arrive_bill === currentArrive.value!.billcode && r.status === e_material_storage_status.报检
  )
  if (qrdoc.value!.qualified !== sum(qrcodes.map((r) => r.qty))) {
    showDialog({ title: '错误', message: '数量校验失败' })
    return
  }
  currentArrive!.value!.qualified += qrdoc.value!.qualified!

  db.saveArriveCode()
  qrcodes.forEach((r) => (r.status = e_material_storage_status.合格))
  db.saveQrCode()
  showDialog({ title: '成功', message: '操作成功' })
  clearQrDoc()
}
const submit_by_ml = () => {
  if (qrdoc.value!.unqualified > 0 && qrdoc.value!.qualified > 0) {
    showDialog({ title: '错误', message: '按物码质检，只能全部合格或全部不合格' })
    return
  }
  const q = db.qrcode.find((r) => r.qrcode === trimPrefix(qrdoc.value.qrcode))
  if (!q) {
    showDialog({ title: '错误', message: '找不到条码' })
    return
  }
  if (q.status !== e_material_storage_status.报检) {
    showDialog({ title: '错误', message: '尚未有报检' })
    return
  }
  if (qrdoc.value!.unqualified === q.qty) {
    q.status = e_material_storage_status.冻结
    currentArrive.value!.unqualified += q.qty
  } else if (qrdoc.value!.qualified === q.qty) {
    q.status = e_material_storage_status.合格
    currentArrive.value!.qualified += q.qty
  } else {
    showDialog({ title: '错误', message: '数量不正确' })
    return
  }
  db.saveQrCode()
  db.saveArriveCode()
  showDialog({ title: '成功', message: '操作成功' })
  clearQrDoc()
}
const submit_by_arrive_without_code = () => {
  currentArrive.value!.qualified += qrdoc.value!.qualified
  currentArrive.value!.unqualified += qrdoc.value!.unqualified
  db.saveArriveCode()
  showDialog({ title: '成功', message: '操作成功' })
  clearQrDoc()
}
</script>
